/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.Album;
import com.sesame.domain.Message;
import com.sesame.service.MessageService;

/**
 * @author shubeta
 * 
 */
public class ReplyMessageController extends SimpleFormController {

    private MessageService messageService;
    private String receiver;

    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }

    protected Object formBackingObject(HttpServletRequest request)
            throws Exception {

        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            Message message = messageService.showMessage(Integer
                    .parseInt(messageId));
            receiver = message.getSender();
            return message;
        } else {
            return super.formBackingObject(request);
        }

    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        Message message = (Message) command;

        Integer userId = (Integer) request.getSession().getAttribute("userId");
        String nickName = (String) request.getSession()
                .getAttribute("nickName");
        Date sendTime = new Date();
        message.setSenderId(userId);
        message.setSender(nickName);
        message.setReceiver(receiver);
        message.setSendTime(sendTime);
        message.setState("0");

        Map model = errors.getModel();

        if (messageService.isNewMessage(message, model)) {
            return new ModelAndView("redirect:inbox.html");
        } else {
            return new ModelAndView(getFormView(), model);
        }

    }
}